package com.wolfking.jeesite.config;

import com.wolfking.jeesite.util.CookieUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * sso的配置
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月23日 下午5:11:14
 * @copyright wolfking
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "sso")
public class SsoConfig {
    // 是否进行sso的鉴权
    private boolean enabled = true;
    // 本身工程的根url，一般是http://ip:port,没有斜杠
    private String selfRootUrl = "";
    // 权限异常的url
    private String permissionUrl;
    // 调试用的用户名
    private String debugUserName;

    // 使用request 解析域名
    private boolean selfRootUrlByRequest = true;


    public String getSelfRootUrlByRequest() {
        if (selfRootUrlByRequest) {
            try {
                String baseUrl = getBaseUrl();
                if (StringUtils.isNotBlank(baseUrl)) {
                    return baseUrl.trim();
                }
            } catch (Exception e) {
                log.warn("", e);
            }
        }
        return this.getSelfRootUrl();
    }

    private String getBaseUrl() throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            String contextPath = request.getContextPath();
            String windowOrigin = CookieUtil.getCookie(request, "window_origin");
            if (StringUtils.isNotBlank(windowOrigin)) {
                windowOrigin = URLDecoder.decode(windowOrigin, StandardCharsets.UTF_8.name());
                log.info("window_origin:{}", windowOrigin);
                return windowOrigin + contextPath;
            } else {
                String s = request.getRequestURL().toString();
                log.info("current request url is {}", s);
                URL url = new URL(s);
                String protocol = url.getProtocol();
                String host = url.getHost();
                String port = url.getPort() == -1 ? "" : ":" + url.getPort();
                return protocol + "://" + host + port + contextPath;
            }
        }
        return "";
    }

    public String getRedirectWithPath(String path) {
        return "redirect:" + this.getSelfRootUrlByRequest() + path;
    }
}
